#include <iostream>
#include <string>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <event2/bufferevent_ssl.h>
#include "../../XSSL/XSSLCtx.h"

#ifdef _WIN32
#include <winsock2.h>
#define close(s) closesocket(s)
#define sock_error() WSAGetLastError()
// #define printError(x) WSAPrint
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <signal.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define sock_error() errno
#endif

using namespace std;

void ClientReadCB(struct bufferevent *bev, void *ctx)
{
    char buf[1024] = {0};
    if (bufferevent_read(bev, buf, 1024) > 0)
    {
        printf("ClientReadCB:%s\n", buf);
    }
    else
    {
        printf("ClientReadCB:error\n");
    }
}

void ClientWriteCB(struct bufferevent *bev, void *ctx)
{
}

void ClientEventCB(struct bufferevent *bev, short what, void *ctx)
{
    if (what & BEV_EVENT_CONNECTED)
    {
        printf("ClientConnected\n");
        bufferevent_write(bev, "Hello Server", strlen("Hello Server"));
        // bufferevent_setcb(bev,ClientReadCB,ClientWriteCB,bufferevent_event_cb,ctx);
        // bufferevent_enable(bev,EV_READ|EV_WRITE);
        // bufferevent_write(bev,"Hello Server",strlen("Hello Server"));
    }
    else
    {
        printf("ClientConnectError\n");
    }
}

void ServerReadCB(struct bufferevent *bev, void *ctx)
{
    char buf[1024] = {0};
    if (bufferevent_read(bev, buf, 1024) > 0)
    {
        printf("ClientReadCB:%s\n", buf);
    }
    string str = "hello world";
    bufferevent_write(bev, str.c_str(), str.size());
}
void ServerWriteCB(struct bufferevent *bev, void *ctx)
{
}

void ServerEventCB(struct bufferevent *bev, short what, void *ctx)
{
    if (what & BEV_EVENT_CONNECTED)
    {
        printf("ClientConnected\n");
        bufferevent_write(bev, "Hello Client", strlen("Hello Client"));
        // bufferevent_setcb(bev,ClientReadCB,ClientWriteCB,bufferevent_event_cb,ctx);
        // bufferevent_enable(bev,EV_READ|EV_WRITE);
        // bufferevent_write(bev,"Hello Server",strlen("Hello Server"));
    }
    else
    {
        printf("ClientConnectError\n");
    }
}
void ListeneCB(evconnlistener *listener, intptr_t sock, sockaddr *addr, int socklen, void *arg)
{
    XSSLCtx *ctx = (XSSLCtx *)arg;
    auto base = evconnlistener_get_base(listener);

    XSSL xssl = ctx->NewXSSL(sock);
    XSSL *pxssl = new XSSL(xssl);
    (*pxssl) = xssl;
    bufferevent *bufev = bufferevent_openssl_socket_new(base, sock, pxssl->ssl(), BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE);
    if (!bufev)
    {
        cout << "bufferevent_openssl_socket_new error" << endl;
        return;
    }

    bufferevent_enable(bufev, EV_READ | EV_WRITE);
    bufferevent_setcb(bufev, ServerReadCB, ServerWriteCB, ServerEventCB, NULL);
    // bufferevent_free(bufev);
}

int main(int argc, char *argv[])
{
#ifdef _WIN32
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);
#else
    signal(SIGPIPE, SIG_IGN);
#endif
    int port = 20000;
    if (argc > 1)
    {
        port = atoi(argv[1]);
    }
    struct event_base *base = event_base_new();
    if (!base)
    {
        printf("event_base_new error\n");
        return -1;
    }
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == SOCKET_ERROR)
    {
        cout << "socket error" << endl;
        event_base_free(base);
        return -1;
    }
    XSSLCtx ctx;
    if (argc > 2)
    { // 客户端
        string ip = argv[2];
        ctx.InitClient();
        auto xssl = ctx.NewXSSL(sock);
        bufferevent *bufev = bufferevent_openssl_socket_new(base, sock, xssl.ssl(), BUFFEREVENT_SSL_CONNECTING, BEV_OPT_CLOSE_ON_FREE);
        if (!bufev)
        {
            cout << "bufferevent_openssl_socket_new error" << endl;
            xssl.Close();
            return -1;
        }

        bufferevent_enable(bufev, EV_READ | EV_WRITE);
        bufferevent_setcb(bufev, ClientReadCB, ClientWriteCB, ClientEventCB, NULL);
        sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        bufferevent_socket_connect(bufev, (struct sockaddr *)&addr, sizeof(addr));
        for (;;)
        {
            event_base_loop(base, EVLOOP_NONBLOCK);
        }
        xssl.Close();
        bufferevent_free(bufev);
        return 0;
    }
    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;
    ctx.InitServer("server.crt", "server.key","server.crt");
    evconnlistener *listener = evconnlistener_new_bind(base, ListeneCB, &ctx, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, 10, (struct sockaddr *)&addr, sizeof(addr));
    if (!listener)
    {
        printf("listener create error\n");
        ctx.Close();
        event_base_free(base);
        return -1;
    }
    for (;;)
    {
        event_base_loop(base, EVLOOP_NONBLOCK);
    }

    ctx.Close();
    event_base_free(base);
    return 0;
}